//
//  Fraction.m
//  02-ClassAndObject
//
//  Created by dllo on 16/7/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction
- (instancetype)initWithNumer:(NSInteger)numer withDenom:(NSInteger)denom{
    self = [super init];
    if (self) {
        _numer = numer;
        _denom = denom;
    }
    return self;
}
//求最大公约数
- (NSInteger)maxCommonDivisorWithNum1:(NSInteger)num1 withNum2:(NSInteger)num2 {
    NSInteger temp = 0;
    while (num2 != 0) {
        temp = num1 % num2;
        num1 = num2;
        num2 = temp;
    }
    return num1;
}
//加法
- (Fraction *)addFra1:(Fraction *)fra2 {
    NSInteger newNumertor = self.numer * fra2.denom + self.denom * fra2.numer;
    NSInteger newDenominator = self.denom * fra2.denom;
    Fraction *fra = [[Fraction alloc]initWithNumer:newNumertor withDenom:newDenominator];
    //约分
    [fra reduce];
    return fra;
}
//减法
- (Fraction *)subFra:(Fraction *)fra2 {
    NSInteger newNumertor = self.numer * fra2.denom - self.denom * fra2.numer;
    NSInteger newDenominator = self.denom * fra2.denom;
    Fraction *fra = [[Fraction alloc]initWithNumer:newNumertor withDenom:newDenominator];
    //约分
    [fra reduce];
    return fra;
}
//乘法
- (Fraction *)mulFra:(Fraction *)fra2 {
    NSInteger newNumertor = self.numer * fra2.numer;
    NSInteger newDenominator = self.denom * fra2.denom;
    Fraction *fra = [[Fraction alloc]initWithNumer:newNumertor withDenom:newDenominator];
    [fra reduce];
    return fra;
}
//除法
- (Fraction *)divFra:(Fraction *)fra2 {
    NSInteger newNumertor = self.numer * fra2.denom;
    NSInteger newDenominator = self.denom * fra2.numer;
    Fraction *fra = [[Fraction alloc]initWithNumer:newNumertor withDenom:newDenominator];
    [fra reduce];
    return fra;
}
//约分
- (void)reduce {
    NSInteger maxCommonDivisor = [self maxCommonDivisorWithNum1:abs((int)self.numer) withNum2:self.denom];
    self.denom /= maxCommonDivisor;
    self.numer /= maxCommonDivisor;
}
//比较大小
- (void)compareFra:(Fraction *)fra2 {
    NSInteger newNumertor = self.numer * fra2.denom - self.denom * fra2.numer;
   if (newNumertor > 0) {
        NSLog(@"fra1大于fra2");
    } else {
       NSLog(@"fra2大于fra1");
    
    }
}
//直接打印分子分母
- (NSString *)description {
   
    return [NSString stringWithFormat:@"<%ld-%ld>",self.numer,self.denom];
}

@end
